package net.zigin.nhi.waste.view.notify;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.guoqi.actionsheet.ActionSheet;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.AnnounceImgAdapter;
import net.zigin.nhi.waste.adapter.IAdapterUpData;
import net.zigin.nhi.waste.adapter.IAnnounceTypeData;
import net.zigin.nhi.waste.adapter.IAnnounceUpData;
import net.zigin.nhi.waste.adapter.IDialogUpData;
import net.zigin.nhi.waste.bean.BitmapBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.widget.AnnounceTypeDialog;
import net.zigin.nhi.waste.view.widget.DialogManager;
import net.zigin.nhi.waste.view.widget.NotifyReceiverDialog;
import net.zigin.nhi.waste.view.widget.OfficeDialog;
import net.zigin.nhi.waste.view.widget.RoleDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;


/**
 * 发布公告界面
 */
public class AnnounceActivity extends AppCompatActivity implements View.OnClickListener, ActionSheet.OnActionSheetSelected {

    private RelativeLayout mAnnounceTypeLayout;
    private TextView mAnnounceType;
    private RelativeLayout mTypeLayout;
    private TextView mTvType;
    private EditText mType;

    private EditText mTitle;
    private EditText mContent;
    private RelativeLayout mUpload;
    private Button mAnnounce;
    private RecyclerView mRvImg;

    private AnnounceImgAdapter imgAdapter;
    private List<BitmapBean> imgList = new ArrayList<>();       //选择图片列表
    private List<String> urlList = new ArrayList<>();       //上传图片列表

    private String announceType = "depart";                 //发布类型
    private List<String> receivers = new ArrayList<>();     //接收人姓名列表
    private List<String> receiverIDs = new ArrayList<>();   //接收人ID列表
    private String receiverDepartId = "";                   //科室ID
    private String receiverRoleId = "";                     //角色ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_announce);
        initView();
        receiverIDs.clear();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mAnnounceTypeLayout = findViewById(R.id.announce_type_layout);
        mAnnounceType = findViewById(R.id.announce_type);
        mTypeLayout = findViewById(R.id.type_layout);
        mTvType = findViewById(R.id.tv_type);
        mType = findViewById(R.id.type);
        mTitle = findViewById(R.id.title);
        mContent = findViewById(R.id.content);
        mUpload = findViewById(R.id.upload);
        mRvImg = findViewById(R.id.rv_img);
        mAnnounce = findViewById(R.id.announce);

        mAnnounceTypeLayout.setOnClickListener(this);
        mTypeLayout.setOnClickListener(this);
        mAnnounce.setOnClickListener(this);
        mUpload.setOnClickListener(this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        mRvImg.setLayoutManager(manager);
    }

    @Override
    protected void onResume() {
        super.onResume();
        imgAdapter = new AnnounceImgAdapter(imgList, urlDD);
        mRvImg.setAdapter(imgAdapter);
    }

    private IAdapterUpData urlDD = new IAdapterUpData() {
        @Override
        public void upDataUi(List<String> list) {
            urlList.addAll(list);
        }
    };

    /**
     * 选择科室对话框返回的选中的科室
     */
    private IDialogUpData officeDD = new IDialogUpData() {
        @Override
        public void upDataUi(String data, String id) {
            if (StringUtil.isNotEmpty(data)) {
                mType.setText(data);
                receiverDepartId = id;
            }
        }
    };

    /**
     * 选择角色对话框返回的选中的角色
     */
    private IDialogUpData roleDD = new IDialogUpData() {
        @Override
        public void upDataUi(String data, String id) {
            if (StringUtil.isNotEmpty(data)) {
                mType.setText(data);
                receiverRoleId = id;
            }
        }
    };

    /**
     * 选择接收人对话框返回的选中的接收人
     */
    private IAnnounceUpData dd = new IAnnounceUpData() {
        @Override
        public void upDataUi(List<String> nameList, List<String> idList) {
            String tv = "";
            for (String name : nameList) {
                tv = tv + " " + name;
            }
            mType.setText(tv);

            receivers.addAll(nameList);
            receiverIDs.addAll(idList);
        }
    };

    /**
     * 发布类型对话框返回选中的类型
     */
    private IAnnounceTypeData typeDD = new IAnnounceTypeData() {
        @Override
        public void upDataUi(String type) {
            if (StringUtil.isNotEmpty(type)) {
                announceType = type;
                switch (type) {
                    case "depart":
                        mAnnounceType.setText("科室");
                        mTvType.setText("科室");
                        mType.setHint("请选择所属科室");
                        mType.setText("");
                        break;
                    case "role":
                        mAnnounceType.setText("角色");
                        mTvType.setText("角色");
                        mType.setHint("请选择角色");
                        mType.setText("");
                        break;
                    case "staff":
                        mAnnounceType.setText("接收人");
                        mTvType.setText("接收人");
                        mType.setHint("请选择接收人");
                        mType.setText("");
                        break;
                }
            }
        }
    };

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.announce_type_layout:  //发布类型栏
                AnnounceTypeDialog typeDialog = AnnounceTypeDialog.getInstance(this, AnnounceActivity.this, typeDD);
                typeDialog.show();
                break;
            case R.id.type_layout:      //具体类型栏
                switch (mAnnounceType.getText().toString()) {
                    case "科室":
                        if (StringUtil.isEmpty(mType.getText().toString())) {
                            OfficeDialog.mInstance = null;
                            OfficeDialog officeDialog =  OfficeDialog.getInstance(this, AnnounceActivity.this, officeDD);
                            officeDialog.show();
                        } else {
                            OfficeDialog officeDialog =  OfficeDialog.getInstance(this, AnnounceActivity.this, officeDD);
                            officeDialog.show();
                        }
                        break;
                    case "角色":
                        RoleDialog roleDialog = RoleDialog.getInstance(this, AnnounceActivity.this, roleDD);
                        roleDialog.show();
                        break;
                    case "接收人":
                        if (receivers.size() > 0) {
                            NotifyReceiverDialog.mInstance = null;
                            NotifyReceiverDialog dialog = NotifyReceiverDialog.getInstance(this, AnnounceActivity.this, dd);
                            dialog.show();
                        } else {
                            NotifyReceiverDialog dialog = NotifyReceiverDialog.getInstance(this, AnnounceActivity.this, dd);
                            dialog.show();
                        }
                        break;
                }
                break;
            case R.id.upload:
                ActionSheet.showSheet(AnnounceActivity.this, this, null);
                break;
            case R.id.announce:
                if (StringUtil.isEmpty(mTitle.getText().toString()) || StringUtil.isEmpty(mContent.getText().toString()) || StringUtil.isEmpty(mType.getText().toString())) {
                    Toast.makeText(AnnounceActivity.this, "请填写完整信息！", Toast.LENGTH_SHORT).show();
                } else {
                    if (urlList.size() > 0) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("title", mTitle.getText().toString());
                        map.put("content", mContent.getText().toString());
                        map.put("type", announceType);
                        switch (announceType) {
                            case "depart":
                                map.put("receiverDepartId", receiverDepartId);
                                break;
                            case "role":
                                map.put("receiverRoleId", receiverRoleId);
                                break;
                            case "staff":
                                map.put("receiverIds", receiverIDs);
                                break;
                        }
                        map.put("picUrl", urlList);
                        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                                .saveNotify(Paper.book().read(Constants.TOKEN), map);
                        DialogManager.getInstance().showLoading(this);
                        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                            @Override
                            protected void success(String data) {
                                Toast.makeText(AnnounceActivity.this, "发布成功！", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        });
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        map.put("title", mTitle.getText().toString());
                        map.put("content", mContent.getText().toString());
                        map.put("type", announceType);
                        switch (announceType) {
                            case "depart":
                                map.put("receiverDepartId", receiverDepartId);
                                break;
                            case "role":
                                map.put("receiverRoleId", receiverRoleId);
                                break;
                            case "staff":
                                map.put("receiverIds", receiverIDs);
                                break;
                        }
                        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                                .saveNotify(Paper.book().read(Constants.TOKEN), map);
                        DialogManager.getInstance().showLoading(this);
                        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                            @Override
                            protected void success(String data) {
                                Toast.makeText(AnnounceActivity.this, "发布成功！", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        });
                    }
                }

                break;
        }
    }

    @Override
    public void onClick(int whichButton) {
        switch (whichButton) {
            case ActionSheet.CHOOSE_PICTURE:
                //相册
                choosePic();
                break;
            case ActionSheet.TAKE_PICTURE:
                //拍照
                takePic();
                break;
            case ActionSheet.CANCEL:
                //取消
                break;
        }
    }

    /**
     * 选择本地图片
     */
    private void choosePic() {
        Intent it = new Intent();
        it.setType("image/*");
        it.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(it, 2);
    }

    /**
     * 拍照
     */
    private void takePic() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);
    }

    float scale;

    //为了适应不同屏幕的显示
    public int getPixel(int old) {
        return (int) (old * scale + 0.5f);
    }

    // 对分辨率较大的图片进行缩放
    public Bitmap zoomBitmap(Bitmap bitmap, float width, float height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);

        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Uri mImageCaptureUri = data.getData();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(getPixel(300), getPixel(250));
            params.setMargins(0, 15, 0, 15);
            if (mImageCaptureUri != null) {
                try {
                    //这个方法是根据Uri获取Bitmap图片的静态方法
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageCaptureUri);
                    // 获取屏幕分辨率
                    DisplayMetrics dm_2 = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm_2);
                    // 图片分辨率与屏幕分辨率比例
                    float scale_2 = bitmap.getWidth() / (float) dm_2.widthPixels;

                    Bitmap newBitMap = null;
                    if (scale_2 > 1) {
                        newBitMap = zoomBitmap(bitmap, bitmap.getWidth() / scale_2, bitmap.getHeight() / scale_2);
                        bitmap.recycle();
                    }

                    if (imgList.size() < 5) {
                        BitmapBean bean = new BitmapBean();
                        bean.setBitmap(newBitMap);
                        bean.setUpload(false);
                        imgList.add(bean);
                    } else {
                        Toast.makeText(getApplicationContext(), "最多上传5张图片！", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                    Bitmap image = extras.getParcelable("data");
                    if (image != null) {
                        if (imgList.size() < 5) {
                            BitmapBean bean = new BitmapBean();
                            bean.setBitmap(image);
                            bean.setUpload(false);
                            imgList.add(bean);
                        } else {
                            Toast.makeText(getApplicationContext(), "最多上传5张图片！", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OfficeDialog.mInstance = null;
        RoleDialog.mInstance = null;
        NotifyReceiverDialog.mInstance = null;
        AnnounceTypeDialog.mInstance = null;
    }
}